import requests
import re
class QSBK:
    def __init__(self):
        self.pageIndex = 1
        self.headers = {
            'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.104 Safari/537.36 Core/1.53.3538.400 QQBrowser/9.6.12501.400',
            'Cookie':'_xsrf=2|eb9eb34d|cd416039ac87f0e36c5bae0e71e11fca|1509632722; ADEZ_BLOCK_SLOT=FUCKIE; ADEZ_ST=FUCKIE; ADEZ_Source=www.baidu.com/s; __cur_art_index=704; ADEZ_ASD=1; ADEZ_PVC=1026761-10-j9j1p4u7; _ga=GA1.2.767623003.1509632729; _gid=GA1.2.864697670.1509632730; Hm_lvt_2670efbdd59c7e3ed3749b458cafaa37=1509632762; Hm_lpvt_2670efbdd59c7e3ed3749b458cafaa37=1509633075'
        }
        self.stories = []
        self.enable = False
    def getPage(self,pageIndex):
        try:
            url = 'https://www.qiushibaike.com/hot/page/'+ str(pageIndex)
            pagecode = requests.get(url,headers=self.headers).text
            return pagecode
        except:
            pass

    def getPageItems(self,pageIndex):
        pagecode = self.getPage(pageIndex)
        if not pagecode:
            print("404")
            return None
        pattern = re.compile('''<div.*?author clearfix">.*?<h2>(.*?)</h2>.*?content">.*?span>(.*?)</span>''' + '''.*?<!-- 图片或gif -->(.*?)<div class="stats">''',re.S)
        items = re.findall(pattern,pagecode)
        pageStories =[]
        for item in items:
            haveImg = re.search("img",item[2])
            if not haveImg:
                replaceBR = re.compile('<br/>')
                text = re.sub(replaceBR,"\n",item[1])
                pageStories.append([item[0].strip(),text.strip()])
        return pageStories

    def loadPage(self):
        if self.enable == True:
            if len(self.stories) < 2:
                pageStories = self.getPageItems(self.pageIndex)
                if pageStories:
                    self.stories.append((pageStories))
                    self.pageIndex += 1

    def getOneStory(self,pageStories,page):
        for story in pageStories:
            inputnext = input()
            self.loadPage()
            if inputnext == "Q":
                self.enable = False
                return
            print ("page:{}\nauthor:{}\ntext:{}".format(page,story[0],story[1]))

    def start(self):
        print('Starting...,Enter for NextStory,Q for Exit')
        self.enable = True
        self.loadPage()
        nowPage = 0
        while self.enable:
            pageStories = self.stories[0]
            nowPage += 1
            del self.stories[0]
            self.getOneStory(pageStories,nowPage)

spider = QSBK()
spider.start()